package com.mine.modules.base.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mine.common.domain.dto.LoginModel;
import com.mine.common.domain.query.ExcelQuery;
import com.mine.common.domain.vo.Result;
import com.mine.common.utils.AnnotationUtil;
import com.mine.modules.vm.common.constant.BizConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description: Controller基类
 */
@Slf4j
public class BaseCommonController<T, S extends IService<T>> {
    @Autowired
    protected S service;

    /**
     * 导出excel
     */
    protected void exportXls(HttpServletResponse response, Class<T> clazz, ExcelQuery excelQuery) throws IOException {
        LoginModel sysUser = (LoginModel) SecurityUtils.getSubject().getPrincipal();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String title = StringUtils.isEmpty(excelQuery.getTitle()) ? BizConstant.EXCEL_EXPORT_DEFAULT_NAME : excelQuery.getTitle();
        String fileName = URLEncoder.encode(title, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        //查询条件关键字keywords解析
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(excelQuery.getKeywords())) {
            wrapper = AnnotationUtil.processCommonSearchKeywords(wrapper, clazz, excelQuery.getKeywords());
        }
        List<T> list = service.list(wrapper);
        //数据字典转换
        EasyExcel.write(response.getOutputStream(), clazz)
                .autoCloseStream(Boolean.FALSE)
                .sheet(title)
                .doWrite(list);
    }

    /**
     * 通过excel导入数据
     */
    protected Result<?> importExcel(MultipartFile file, Class<T> clazz) {
        try {
            if (file == null || file.isEmpty()) {
                return Result.error("文件不能为空");
            }
            List<T> list = EasyExcel.read(file.getInputStream()).head(clazz)
//                        .registerConverter(new CustomConverter())
                    .sheet().headRowNumber(3)
                    .doReadSync();
            if (list.isEmpty()) {
                return Result.error("文件数据解析为空！");
            }
            service.saveBatch(list);
        } catch (IOException e) {
            log.error("导入失败", e);
            return Result.error("导入失败：" + e.getMessage());
        }
        return Result.ok("导入成功！");
    }

}
